package com.mo.demo.guava;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
public class GuavaTest2 {
    public static void main(String[] args) throws InterruptedException {

        // 写缓存后3秒会过期
        Cache<String, String> cache = CacheBuilder.newBuilder()
                .expireAfterAccess(3, TimeUnit.SECONDS)
                .build();

        cache.put("1","111");

        int time = 1;

        while (true){
            log.info("第{}次获取缓存值，value={}",time,cache.getIfPresent("1"));
            time++;
            Thread.sleep(1000);
        }

        // 输出：
        // 14:13:17.172 [main] INFO com.mo.demo.guava.GuavaTest2 - 第1次获取缓存值，value=111
        // 14:13:18.180 [main] INFO com.mo.demo.guava.GuavaTest2 - 第2次获取缓存值，value=111
        // 14:13:19.181 [main] INFO com.mo.demo.guava.GuavaTest2 - 第3次获取缓存值，value=111
        // 14:13:20.190 [main] INFO com.mo.demo.guava.GuavaTest2 - 第4次获取缓存值，value=null
        // 14:13:21.192 [main] INFO com.mo.demo.guava.GuavaTest2 - 第5次获取缓存值，value=null
        // 14:13:22.192 [main] INFO com.mo.demo.guava.GuavaTest2 - 第6次获取缓存值，value=null
        // 14:13:23.192 [main] INFO com.mo.demo.guava.GuavaTest2 - 第7次获取缓存值，value=null
        // ...

    }
}
